<template>
    <el-form inline="true" class="search-form">
      <el-form-item label="创建日期">
        <el-date-picker v-model="datetimeRange" style="width: 240px" type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="竞赛名称">
        <el-input v-model="params.title" placeholder="请您输入要搜索的竞赛名称" />
      </el-form-item>
      <el-form-item>
        <el-button @click="onSearch" plain :class="{ 'loading': searchLoading }">
            <el-icon v-if="searchLoading" class="is-loading"><Loading /></el-icon>
            <el-icon v-else><Search /></el-icon>
            搜索
        </el-button>
        <el-button @click="onReset" plain type="info" :class="{ 'loading': resetLoading }">
            <el-icon v-if="resetLoading" class="is-loading"><Loading /></el-icon>
            <el-icon v-else><Refresh /></el-icon>
            重置
        </el-button>
        <el-button type="primary" plain @click="onAddExam" :class="{ 'loading': addLoading }">
            <el-icon v-if="addLoading" class="is-loading"><Loading /></el-icon>
            <el-icon v-else><Plus /></el-icon>
            添加竞赛
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table height="526px" :data="examList" v-loading="tableLoading">
      <el-table-column prop="title" label="竞赛标题"/>
      <el-table-column prop="startTime" width="180px" label="竞赛开始时间" />
      <el-table-column prop="endTime" width="180px" label="竞赛结束时间" />
      <el-table-column label="是否开赛" width="100px">
        <template #default="{ row }">
          <div v-if="!isNotStartExam(row)">
            <el-tag type="warning">已开赛</el-tag>
          </div>
          <div v-else>
            <el-tag type="info">未开赛</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" width="100px" label="是否发布">
        <template #default="{ row }">
          <div v-if="row.status == 0">
            <el-tag type="danger">未发布</el-tag>
          </div>
          <div v-if="row.status == 1">
            <el-tag type="success">已发布</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createName" width="140px" label="创建用户" />
      <el-table-column prop="createTime" width="180px" label="创建时间" />
      <el-table-column label="操作" width="180px">
        <template #default="{ row }">
          <el-button v-if="isNotStartExam(row) && row.status == 0" type="text" @click="onEdit(row.examId)">编辑
          </el-button>
          <el-button v-if="isNotStartExam(row) && row.status == 0" type="text" @click="onDelete(row.examId)" class="red">删除
          </el-button>
          <el-button v-if="row.status == 1 && isNotStartExam(row)" type="text"
            @click="cancelPublishExam(row.examId)">撤销发布</el-button>
          <el-button v-if="row.status == 0 && isNotStartExam(row)" type="text"
            @click="publishExam(row.examId)">发布</el-button>
          <el-button type="text" v-if="!isNotStartExam(row)">已开赛，不允许操作</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination background size="small" layout="total, sizes, prev, pager, next, jumper" :total="total"
      v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 15, 20]"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </template>
  <script setup>
import { Plus, Search, Refresh, Loading } from '@element-plus/icons-vue'
import { getExamDetailService, getExamListService, deleteExamService, publishExamService, cancelPublishExamService } from '@/apis/exam'
import { reactive,ref } from 'vue'
import router from '@/router'
import { ElMessageBox, ElMessage } from 'element-plus'


function isNotStartExam(exam) {
    //返回true则还没开始
  const now = new Date(); //当前时间
  return new Date(exam.startTime) > now
}
const params= reactive({
    pageNum: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    title: ''

})


const examList = ref([])
const total=ref(0)
const datetimeRange=ref([])
const searchLoading = ref(false)
const resetLoading = ref(false)
const addLoading = ref(false)
const tableLoading = ref(false)




async function getExamList() {
    tableLoading.value = true
    try {
        if (datetimeRange.value[0] instanceof Date) {
            params.startTime = datetimeRange.value[0].toISOString()
        }
        if (datetimeRange.value[1] instanceof Date) {
            params.endTime = datetimeRange.value[1].toISOString()
        }
        const result = await getExamListService(params);    
        console.log(result);
        examList.value=result.rows
        total.value=result.total
        
    } catch (error) {
        ElMessage.error('获取竞赛列表失败')
    } finally {
        tableLoading.value = false
    }
}
getExamList()
function handleSizeChange(newSize){
    params.pageNum=1
    getExamList()



}
function handleCurrentChange(newPage){
    getExamList()

}   
async function onSearch(){
    searchLoading.value = true
    try {
        params.pageNum = 1
        await getExamList()
        ElMessage.success('搜索成功')
    } catch (error) {
        ElMessage.error('搜索失败')
    } finally {
        searchLoading.value = false
    }
}
async function onReset(){
    resetLoading.value = true
    try {
        params.pageNum = 1
        params.pageSize = 10
        params.title = ''
        params.startTime = ''
        params.endTime = ''
        datetimeRange.value = []
        await getExamList()
        ElMessage.success('重置成功')
    } catch (error) {
        ElMessage.error('重置失败')
    } finally {
        resetLoading.value = false
    }
}
async function onAddExam(){
    addLoading.value = true
    try {
        router.push("/oj/layout/updateExam?type=add")
    } finally {
        addLoading.value = false
    }
}

async function onEdit(examId){

  // await getExamDetailService(examId)
  router.push(`/oj/layout/updateExam?type=edit&examId=${examId}`)
}

const onDelete = async (examId) => {
    try {
        await ElMessageBox.confirm("确定要删除该竞赛吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        });
        await deleteExamService(examId);
        ElMessage.success("删除成功");
        getExamList();
    } catch (error) {
        if (error !== "cancel") {
            ElMessage.error("删除失败");
        }
    }
};

const publishExam = async (examId) => {
    try {
        await publishExamService(examId);
        ElMessage.success("发布成功");
        getExamList();
    } catch (error) {
        // 只显示后端返回的错误信息，避免重复显示
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
        }
    }
};

const cancelPublishExam = async (examId) => {
    try {
        await cancelPublishExamService(examId);
        ElMessage.success("撤销发布成功");
        getExamList();
    } catch (error) {
        // 只显示后端返回的错误信息，避免重复显示
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
        }
    }
};

</script>
<style lang="scss" scoped>
.search-form {
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .el-form-item {
        margin-bottom: 0;
    }
    
    .el-button {
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        
        &.loading {
            cursor: not-allowed;
            opacity: 0.8;
        }
        
        .el-icon {
            margin-right: 4px;
            
            &.is-loading {
                animation: rotating 2s linear infinite;
            }
        }
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__row {
        transition: all 0.3s ease;
        
        &:hover {
            background-color: #f5f7fa;
        }
    }
}
</style>